package com.friend.joey.applicationfriend;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Joey on 2017/4/26.
 */

public class CGetPosition extends AppCompatActivity{
    private TextView txt_position;
    private Button btn_position;
    private MyHandler mHandler;

    private MapView mapView;
    private BaiduMap baiduMap;
    public LocationClient mLocationClient;

    private List<String> permissonList = new ArrayList<>();
    private  boolean isFirstLocate = true;

    //Handler与聊天界面线程传数据
    private class MyHandler extends Handler {
        private WeakReference<CGetPosition> mWeakReference;
        public MyHandler(CGetPosition activity){
            mWeakReference=new WeakReference<CGetPosition>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            CGetPosition activity= mWeakReference.get();
            if(activity!=null){
                switch(msg.what){
                    case 1:
                        //Toast.makeText(activity, "成功", Toast.LENGTH_SHORT).show();
                        txt_position.setText(msg.obj.toString());
                        break;
                    case 2:
                        if(isFirstLocate){
                            LatLng ll = new LatLng(((BDLocation)msg.obj).getLatitude(),((BDLocation)msg.obj).getLongitude());
                            MapStatus newMapStatus = new MapStatus.Builder().target(ll).zoom(16).build();
                            //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(newMapStatus);
                            baiduMap.animateMapStatus(mMapStatusUpdate,250);
                            //Toast.makeText(activity, Double.toString(((BDLocation)msg.obj).getLatitude())+" "+Double.toString(((BDLocation)msg.obj).getLongitude()), Toast.LENGTH_SHORT).show();
                            isFirstLocate=false;
                        }
                        MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
                        locationBuilder.latitude(((BDLocation)msg.obj).getLatitude());
                        locationBuilder.longitude(((BDLocation)msg.obj).getLongitude());
                        MyLocationData locationData = locationBuilder.build();
                        baiduMap.setMyLocationData(locationData);
                        break;
                    case -1:
                        Toast.makeText(activity, "失败", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(activity, "没有信息", Toast.LENGTH_SHORT).show();
                }
            }
            else{
                Toast.makeText(activity, "错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        mLocationClient = new LocationClient(getApplicationContext());//声明类
        mLocationClient.registerLocationListener(new MyLocationListener());//注册监听函数
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.c_position );
        mapView = (MapView)findViewById(R.id.bmapView);
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        txt_position=(TextView)findViewById(R.id.txt_cposition);
        //btn_position=(Button)findViewById(R.id.btn_cposition);

        mHandler = new MyHandler(this);//////

        requestLocation();
        DrawHome();

    }
    private void DrawHome(){
        //定义Maker坐标点
        LatLng point = new LatLng(37.5330929990,122.08964860478);
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.childtrace);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        baiduMap.addOverlay(option);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    private void requestLocation(){
        initLocation();
        mLocationClient.start();
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true);
        option.setCoorType("bd09ll");//关键，默认gcj02，导致定位有很大偏差
        //option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.setScanSpan(5000);//5秒更新一次位置
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }

    //位置显示函数，调用handler，从线程返回函数
    private void showLocation(StringBuilder location){
        Message message = mHandler.obtainMessage();
        message.what = 1;
        message.obj = location;
        mHandler.sendMessage(message);
    }

    private void navigateTo(BDLocation location){
        /*if(isFirstLocate){
            LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());
            MapStatusUpdate update= MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update=MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(update);
            isFirstLocate=false;
        }*/

        Message message = mHandler.obtainMessage();
        message.what = 2;
        message.obj = location;
        mHandler.sendMessage(message);

    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {

            StringBuilder currentPosition = new StringBuilder();
            currentPosition.append("纬度：").append(bdLocation.getLatitude()).append("\n");
            currentPosition.append("经线：").append(bdLocation.getLongitude()).append("\n");
            currentPosition.append("国家：").append(bdLocation.getCountry()).append("\n");
            currentPosition.append("省：").append(bdLocation.getProvince()).append("\n");
            currentPosition.append("市：").append(bdLocation.getCity()).append("\n");
            currentPosition.append("区：").append(bdLocation.getDistrict()).append("\n");
            currentPosition.append("街道：").append(bdLocation.getStreet()).append("\n");
            currentPosition.append("定位方式：");
            if(bdLocation.getLocType()==BDLocation.TypeGpsLocation){
                navigateTo(bdLocation);
                currentPosition.append("GPS");
                Toast.makeText(CGetPosition.this, "GPS", Toast.LENGTH_SHORT).show();
            }else if(bdLocation.getLocType()==BDLocation.TypeNetWorkLocation){
                navigateTo(bdLocation);
                currentPosition.append("网络");
                Toast.makeText(CGetPosition.this, "网络", Toast.LENGTH_SHORT).show();
            }else if(bdLocation.getLocType()==BDLocation.TypeOffLineLocation){
                navigateTo(bdLocation);
                currentPosition.append("离线");
                Toast.makeText(CGetPosition.this, "离线", Toast.LENGTH_SHORT).show();
            }else if (bdLocation.getLocType() == BDLocation.TypeServerError){
                currentPosition.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkException) {
                currentPosition.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (bdLocation.getLocType() == BDLocation.TypeCriteriaException) {
                currentPosition.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }else {
                currentPosition.append(Integer.toString(bdLocation.getLocType()));
            }
            //Toast.makeText(CGetPosition.this,currentPosition.toString(), Toast.LENGTH_SHORT).show();
            showLocation(currentPosition);//显示在页面上

        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

}
